package edu.hubu.talentmanagementsystem.controller.impl;

import com.wf.captcha.utils.CaptchaUtil;
import edu.hubu.talentmanagementsystem.auth.JwtGrantedAuthority;
import edu.hubu.talentmanagementsystem.auth.JwtToken;
import edu.hubu.talentmanagementsystem.auth.JwtUtils;
import edu.hubu.talentmanagementsystem.auth.Payload;
import edu.hubu.talentmanagementsystem.common.CommonResult;
import edu.hubu.talentmanagementsystem.common.RedisUtils;
import edu.hubu.talentmanagementsystem.common.RoleType;
import edu.hubu.talentmanagementsystem.service.LoginService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * @author moonlan
 * date 2021/3/17 下午5:53
 */
@SuppressWarnings(value = "unused")
@RestController
@RequestMapping("/user")
public class LoginController {

    private final LoginService loginService;
    private final RedisUtils redisUtils;

    public LoginController(LoginService loginService, RedisUtils redisUtils) {
        this.loginService = loginService;
        this.redisUtils = redisUtils;
    }

    @PostMapping("/login")
    public CommonResult login(String username, String password, String code, HttpServletRequest request) {
        return loginService.login(username, password, code, request);
    }

    @PostMapping("/logout")
    //TODO: 出现302
    @PreAuthorize("hasAnyAuthority('ADMIN', 'STAFF', 'COMPANY')")
    public CommonResult logout(HttpServletRequest request, HttpServletResponse response, @RequestHeader(
            "Authorization") String token) {
        return loginService.logout(request, response);
    }

    @GetMapping("/test-get-token")
    public CommonResult getTestToken() {
        Payload payload =
                new Payload().setRoleName(RoleType.ADMIN).setUserName("test").setAuthorities(Collections.singletonList(new JwtGrantedAuthority("ADMIN")));
        String token =
                JwtUtils.getToken(payload);
        JwtToken jwtToken = new JwtToken(token, payload.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(jwtToken);
        redisUtils.addToken(token);
        return CommonResult.success(token);
    }

    @GetMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response) {
        try {
            CaptchaUtil.out(request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
